package com.sinosoft.ebusiness.servlet;

import com.bugull.mongo.BuguConnection;
import com.bugull.mongo.BuguFramework;
import com.mongodb.MongoClientOptions;
import com.sinosoft.ebusiness.dao.NspExceptionLogDao;
import com.sinosoft.ebusiness.dao.NspInterLogDao;
import com.sinosoft.ebusiness.util.InitProperties;
import com.sinosoft.ebusiness.util.MongoUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MySystemListener implements ServletContextListener {
    private String MONGO_HOST ="mongo.host";
    private String MONGO_PORT ="mongo.port";
    private String MONGO_USER ="mongo.userName";
    private String MONGO_PASS = "mongo.password";
    private String MONGO_DB = "mongo.defaultDbName";

    private static Properties p = new Properties();

    private static final String configFile = "/config/mongo.properties";

    {
        InputStream inStream = this.getClass().getResourceAsStream(configFile);
        try {
            p.load(inStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(200).build();  //使用20个连接

        //连接数据库
        BuguConnection conn = BuguFramework.getInstance().createConnection().setOptions(options);
        conn.connect(p.getProperty(MONGO_HOST),
                Integer.valueOf(p.getProperty(MONGO_PORT)),
                p.getProperty(MONGO_DB),
                p.getProperty(MONGO_USER),
                p.getProperty(MONGO_PASS));
        init();
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        BuguFramework.getInstance().destroy();
    }

    void init(){
        NspInterLogDao nspInterLogDao = new NspInterLogDao();
        NspExceptionLogDao nspExceptionLogDao = new NspExceptionLogDao() ;
        MongoUtils.addBuguDao("nspInterLogDao",nspInterLogDao);
        MongoUtils.addBuguDao("nspExceptionLogDao",nspExceptionLogDao);
    }
}
